<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>视频播放系统</title>
  <!-- Hls.js CDN -->
  <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
  <style>
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .video-list {
      margin-top: 20px;
    }
    .video-item {
      border: 1px solid #ddd;
      padding: 15px;
      margin-bottom: 10px;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .video-info {
      flex: 1;
    }
    .video-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 5px;
    }
    .video-desc {
      color: #666;
      margin-bottom: 5px;
    }
    .video-status {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 3px;
      font-size: 14px;
      margin-right: 10px;
    }
    .status-ready {
      background-color: #e6f7e6;
      color: #2e7d32;
    }
    .status-pending {
      background-color: #fff3e0;
      color: #ef6c00;
    }
    .status-error {
      background-color: #ffebee;
      color: #c62828;
    }
    .play-btn {
      background-color: #1976d2;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
    }
    .play-btn:hover {
      background-color: #1565c0;
    }
    .play-btn:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
    .search-box {
      margin-bottom: 20px;
    }
    .search-input {
      padding: 8px;
      width: 300px;
      border: 1px solid #ddd;
      border-radius: 4px;
      margin-right: 10px;
    }
    .search-btn {
      padding: 8px 16px;
      background-color: #1976d2;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      gap: 10px;
    }
    .page-btn {
      padding: 5px 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
    }
    .page-btn.active {
      background-color: #1976d2;
      color: white;
      border-color: #1976d2;
    }
    /* 上传相关样式 */
    .upload-section {
      margin: 20px 0;
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: #f9f9f9;
    }
    .upload-form {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      align-items: start;
    }
    .file-input-wrapper {
      grid-column: 1 / -1;
      position: relative;
    }
    .file-input {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: white;
      height: 38px;
    }
    .file-input::-webkit-file-upload-button {
      background-color: #1976d2;
      color: white;
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 10px;
      height: 100%;
    }
    .file-input::-webkit-file-upload-button:hover {
      background-color: #1565c0;
    }
    .upload-btn {
      grid-column: 1 / -1;
      padding: 8px 16px;
      background-color: #1976d2;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      height: 38px;
    }
    .upload-btn:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
    .upload-progress {
      margin-top: 10px;
      display: none;
    }
    .progress-bar {
      width: 100%;
      height: 20px;
      background-color: #f0f0f0;
      border-radius: 10px;
      overflow: hidden;
    }
    .progress-fill {
      height: 100%;
      background-color: #4caf50;
      width: 0;
      transition: width 0.3s ease;
    }
    .progress-text {
      margin-top: 5px;
      text-align: center;
      color: #666;
    }
    .error-message {
      color: #d32f2f;
      margin-top: 5px;
      display: none;
    }
    /* 视频播放弹框样式 */
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 1000;
    }
    .modal-content {
      position: relative;
      background-color: #fff;
      margin: 5% auto;
      padding: 20px;
      width: 80%;
      max-width: 1000px;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .close-modal {
      position: absolute;
      right: 20px;
      top: 10px;
      font-size: 24px;
      font-weight: bold;
      color: #666;
      cursor: pointer;
      z-index: 1001;
    }
    .close-modal:hover {
      color: #000;
    }
    .modal-video-container {
      width: 100%;
      margin-top: 20px;
    }
    .modal-video {
      width: 100%;
      aspect-ratio: 16/9;
      background-color: #000;
    }
    .modal-title {
      margin: 0 0 20px 0;
      font-size: 18px;
      color: #333;
    }
  </style>
</head>
<body>
<div class="container">
  <h1>视频播放系统</h1>

  <!-- 上传部分 -->
  <div class="upload-section">
    <form id="uploadForm" class="upload-form">
      <div class="file-input-wrapper">
        <input type="file"
               id="videoFile"
               class="file-input"
               accept="video/mp4"
               onchange="validateFile(this)">
        <div id="errorMessage" class="error-message"></div>
      </div>
      <input type="text"
             id="videoTitle"
             placeholder="视频标题"
             required
             class="search-input">
      <input type="text"
             id="videoDesc"
             placeholder="视频描述"
             class="search-input">
      <button type="submit"
              id="uploadBtn"
              class="upload-btn"
              disabled>
        上传视频
      </button>
    </form>
    <div id="uploadProgress" class="upload-progress">
      <div class="progress-bar">
        <div id="progressFill" class="progress-fill"></div>
      </div>
      <div id="progressText" class="progress-text">0%</div>
    </div>
  </div>

  <!-- 搜索框 -->
  <div class="search-box">
    <input type="text" id="searchInput" class="search-input" placeholder="输入视频标题搜索">
    <button onclick="searchVideos()" class="search-btn">搜索</button>
  </div>

  <!-- 视频列表 -->
  <div class="video-list" id="videoList"></div>

  <!-- 分页 -->
  <div class="pagination" id="pagination"></div>
</div>

<!-- 视频播放弹框 -->
<div id="videoModal" class="modal">
  <div class="modal-content">
    <span class="close-modal" onclick="closeVideoModal()">&times;</span>
    <h3 class="modal-title" id="modalVideoTitle"></h3>
    <div class="modal-video-container">
      <video
              id="modalVideo"
              class="modal-video"
              controls
              autoplay
              muted
      ></video>
    </div>
  </div>
</div>

<script>
  let currentPage = 1;
  let pageSize = 10;
  let currentTitle = '';
  let hls = null;

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function () {
    loadVideos();
  });

  // 加载视频列表
  async function loadVideos() {
    try {
      const response = await fetch(`/api/videos/getVideos?page=${currentPage}&size=${pageSize}&title=${currentTitle}`);
      const data = await response.json();
      renderVideoList(data);
      renderPagination(data);
    } catch (error) {
      console.error('加载视频列表失败:', error);
    }
  }

  // 渲染视频列表
  function renderVideoList(data) {
    const videoList = document.getElementById('videoList');
    videoList.innerHTML = data.list.map(video => `
        <div class="video-item">
          <div class="video-info">
            <div class="video-title">${video.title}</div>
            <div class="video-desc">${video.description || '暂无描述'}</div>
            <div>
              <span class="video-status status-${video.status.toLowerCase()}">
                ${getStatusText(video.status)}
              </span>
            </div>
          </div>
          <button
            class="play-btn"
            onclick="playVideo('${video.id}', '${video.title}')"
            ${video.status !== 'READY' ? 'disabled' : ''}
          >
            播放
          </button>
        </div>
      `).join('');
  }

  // 渲染分页
  function renderPagination(data) {
    const pagination = document.getElementById('pagination');
    let html = '';

    // 上一页
    html += `<button class="page-btn" onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>`;

    // 页码
    for (let i = 1; i <= data.pages; i++) {
      html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
    }

    // 下一页
    html += `<button class="page-btn" onclick="changePage(${currentPage + 1})" ${currentPage === data.pages ? 'disabled' : ''}>下一页</button>`;

    pagination.innerHTML = html;
  }

  // 切换页码
  function changePage(page) {
    if (page < 1 || page > document.querySelectorAll('.page-btn').length - 2) return;
    currentPage = page;
    loadVideos();
  }

  // 搜索视频
  function searchVideos() {
    currentTitle = document.getElementById('searchInput').value.trim();
    currentPage = 1;
    loadVideos();
  }

  // 获取状态文本
  function getStatusText(status) {
    const statusMap = {
      'READY': '已完成',
      'PENDING': '处理中',
      'ERROR': '错误'
    };
    return statusMap[status] || status;
  }

  // 播放视频（修改为弹框播放）
  async function playVideo(videoId, videoTitle) {
    try {
      const response = await fetch(`/api/videos/getPlayUrl?id=${videoId}`);
      const playUrl = await response.text();

      // 设置弹框标题
      document.getElementById('modalVideoTitle').textContent = videoTitle;

      // 显示弹框
      const modal = document.getElementById('videoModal');
      modal.style.display = 'block';

      const video = document.getElementById('modalVideo');

      // 如果已经存在 HLS 实例，先销毁它
      if (hls) {
        hls.destroy();
      }

      if (Hls.isSupported()) {
        hls = new Hls();
        hls.loadSource(playUrl);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function() {
          video.play();
        });
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // Safari 原生支持
        video.src = playUrl;
        video.addEventListener('loadedmetadata', function() {
          video.play();
        });
      } else {
        console.error('当前浏览器不支持 HLS 播放');
      }
    } catch (error) {
      console.error('获取播放地址失败:', error);
    }
  }

  // 关闭视频弹框
  function closeVideoModal() {
    const modal = document.getElementById('videoModal');
    const video = document.getElementById('modalVideo');

    // 停止视频播放
    video.pause();
    video.src = '';

    // 销毁 HLS 实例
    if (hls) {
      hls.destroy();
      hls = null;
    }

    // 隐藏弹框
    modal.style.display = 'none';
  }

  // 点击弹框外部关闭
  window.onclick = function(event) {
    const modal = document.getElementById('videoModal');
    if (event.target === modal) {
      closeVideoModal();
    }
  }

  // 按 ESC 键关闭弹框
  document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
      closeVideoModal();
    }
  });

  // 文件验证
  function validateFile(input) {
    const file = input.files[0];
    const errorMessage = document.getElementById('errorMessage');
    const uploadBtn = document.getElementById('uploadBtn');

    // 重置状态
    errorMessage.style.display = 'none';
    uploadBtn.disabled = true;

    if (!file) {
      return;
    }

    // 检查文件类型
    if (file.type !== 'video/mp4') {
      errorMessage.textContent = '请选择 MP4 格式的视频文件';
      errorMessage.style.display = 'block';
      input.value = '';
      return;
    }

    // 检查文件大小（这里设置为 500MB）
    const maxSize = 500 * 1024 * 1024;
    if (file.size > maxSize) {
      errorMessage.textContent = '文件大小不能超过 500MB';
      errorMessage.style.display = 'block';
      input.value = '';
      return;
    }

    // 验证通过，启用上传按钮
    uploadBtn.disabled = false;
  }

  // 处理上传
  document.getElementById('uploadForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const fileInput = document.getElementById('videoFile');
    const titleInput = document.getElementById('videoTitle');
    const descInput = document.getElementById('videoDesc');
    const uploadBtn = document.getElementById('uploadBtn');
    const progressDiv = document.getElementById('uploadProgress');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');

    const file = fileInput.files[0];
    const title = titleInput.value.trim();
    const desc = descInput.value.trim();

    if (!file || !title) {
      return;
    }

    // 准备表单数据
    const formData = new FormData();
    formData.append('file', file);
    formData.append('title', title);
    formData.append('desc', desc);

    try {
      // 禁用上传按钮
      uploadBtn.disabled = true;
      // 显示进度条
      progressDiv.style.display = 'block';

      // 创建 XMLHttpRequest 以支持上传进度
      const xhr = new XMLHttpRequest();

      // 处理上传进度
      xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
          const percent = Math.round((e.loaded / e.total) * 100);
          progressFill.style.width = percent + '%';
          progressText.textContent = percent + '%';
        }
      };

      // 处理上传完成
      xhr.onload = function() {
        if (xhr.status === 200) {
          // 上传成功，刷新视频列表
          alert('视频上传成功！');
          // 重置表单
          fileInput.value = '';
          titleInput.value = '';
          descInput.value = '';
          // 隐藏进度条
          progressDiv.style.display = 'none';
          progressFill.style.width = '0';
          progressText.textContent = '0%';
          // 刷新视频列表
          loadVideos();
        } else {
          alert('上传失败：' + xhr.responseText);
        }
        uploadBtn.disabled = false;
      };

      // 处理上传错误
      xhr.onerror = function() {
        alert('上传失败，请检查网络连接');
        uploadBtn.disabled = false;
        progressDiv.style.display = 'none';
      };

      // 发送请求
      xhr.open('POST', '/api/videos/upload');
      xhr.send(formData);

    } catch (error) {
      console.error('上传失败:', error);
      alert('上传失败，请重试');
      uploadBtn.disabled = false;
      progressDiv.style.display = 'none';
    }
  });
</script>
</body>
</html>
